package com.loiot.baqi.controller.component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.loiot.baqi.constant.Const;
import com.loiot.baqi.pojo.Tables;
import com.loiot.baqi.pojo.ZpDictionaryInfo;
import com.loiot.baqi.service.ZpDictionaryInfoService;
import com.loiot.baqi.utils.IndexInfoSingleTon;


/**
 * CacheInitialize.java
 * 
 * @author: Hinsteny
 * @date: 2016年1月11日
 * @copyright: 2016 All rights reserved.
 * 
 */
@Component
public class CacheInitialize implements InitializingBean {

    @Resource
    private ZpDictionaryInfoService zpDictionaryInfoService;
    
    @Override
    public void afterPropertiesSet() throws Exception {
//        IndexInfoSingleTon indexInfo = IndexInfoSingleTon.getInstance();
//        List<ZpDictionaryInfo> dictList = zpDictionaryInfoService.queryZpDictionaryInfoList(new HashMap<String,Object>());
//         Map<String, List> infoMap = indexInfo.getIndexInfoMap();
//		 infoMap.put(Const.SESSION_DICTIONARYS_KEY, dictList);
//        //获取表及字段 并放到缓存中
//        List<Tables> tablesList = zpDictionaryInfoService.queryTableList();
//        indexInfo.setTables(tablesList);

    	  IndexInfoSingleTon indexInfo = IndexInfoSingleTon.getInstance();
          List<ZpDictionaryInfo> dictList = zpDictionaryInfoService.queryZpDictionaryInfoList(new HashMap<String,Object>());
          indexInfo.setDictCache(loadDict(dictList)); 

          //获取表及字段 并放到缓存中
          List<Tables> tablesList = zpDictionaryInfoService.queryTableList();
          indexInfo.setTables(tablesList);

    }

	/**
	 * 将字典List转为Map.
	 * @param dictList
	 * @return
	 */
	private Map<String, Map<String, ZpDictionaryInfo>> loadDict(List<ZpDictionaryInfo> dictList) {
		Map<String, Map<String, ZpDictionaryInfo>> dictCache = new HashMap<String, Map<String, ZpDictionaryInfo>>();
		if(CollectionUtils.isEmpty(dictList)){
			return dictCache;
		}
		String type = null;
		Map<String, ZpDictionaryInfo> typeMap = null;
		for(ZpDictionaryInfo dictInfo : dictList){
			type = String.valueOf(dictInfo.getType());
			typeMap = dictCache.get(type);
			if(typeMap == null){
				typeMap = new TreeMap<String, ZpDictionaryInfo>();
				dictCache.put(type, typeMap);
			}
			typeMap.put(String.valueOf(dictInfo.getDictionaryId()), dictInfo);
		}
		return dictCache;
	}

}
